package com.feilong.edgeAI.update;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


import com.aiibt.common.bean.AppVersion;
import com.aiibt.common.bean.Result;
import com.feilong.edgeAI.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;


public class UpdateHelper {

	private static final String UPDATE_BASE = "https://pp.aiibt.cn";
	private static final String UPDATE_APK = UPDATE_BASE+"upload/";
	private static final String UPDATE_XXZ = UPDATE_BASE+"upload/";
	private Thread mThread;
	private Context mContext;
	private static final String TAG = "UpdateHelper";
	public UpdateHelper(Context context){
		this.mContext = context;
	}
	
	public void checkForUpdates(final boolean isClick) {
		mThread = new Thread() {
			@Override
			public void run() {
				String json = sendPost(UPDATE_APK);
				if (json != null) {
					parseJson(json,isClick);
				} else {
					Log.e(TAG, "can't get app update json");
				}
			}

		};
//		mThread.start();
//		parseJson(sendPost(UPDATE),isClick);
		RequestParams params = new RequestParams(UPDATE_APK);
		Log.d(TAG, "checkForUpdates: " + params.toString());
		org.xutils.x.http().get(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.d(TAG, "onSuccess: +" + result);
				parseJson(result,isClick);
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				ex.printStackTrace();
			}

			@Override
			public void onCancelled(CancelledException cex) {
				cex.printStackTrace();
			}

			@Override
			public void onFinished() {
			}
		});
	}
	
	protected String sendPost(String urlStr) {
		HttpURLConnection uRLConnection = null;
		InputStream is = null;
		BufferedReader buffer = null;
		String result = null;
		try {
			URL url = new URL(urlStr);
			uRLConnection = (HttpURLConnection) url.openConnection();
			uRLConnection.setDoInput(true);
			uRLConnection.setDoOutput(true);
			uRLConnection.setRequestMethod("POST");
			uRLConnection.setUseCaches(false);
			uRLConnection.setConnectTimeout(10 * 1000);
			uRLConnection.setReadTimeout(10 * 1000);
			uRLConnection.setInstanceFollowRedirects(false);
			uRLConnection.setRequestProperty("Connection", "Keep-Alive");
			uRLConnection.setRequestProperty("Charset", "UTF-8");
			uRLConnection
					.setRequestProperty("Accept-Encoding", "gzip, deflate");
			uRLConnection
					.setRequestProperty("Content-Type", "application/json");

			uRLConnection.connect();

			is = uRLConnection.getInputStream();

			String content_encode = uRLConnection.getContentEncoding();

			if (null != content_encode && !"".equals(content_encode)
					&& content_encode.equals("gzip")) {
				is = new GZIPInputStream(is);
			}

			buffer = new BufferedReader(new InputStreamReader(is));
			StringBuilder strBuilder = new StringBuilder();
			String line;
			while ((line = buffer.readLine()) != null) {
				strBuilder.append(line);
			}
			result = strBuilder.toString();
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "http post error", e);
		} finally {
			if (buffer != null) {
				try {
					buffer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (uRLConnection != null) {
				uRLConnection.disconnect();
			}
		}
		return result;
	}

	public String updateMessage="";
	public String apkUrl="";
	public String version="";
	public static boolean needUpdate=false;
	private void parseJson(String json,boolean isClick) {
		try {
			Gson gson = new Gson();
			Type type = new TypeToken<Result<AppVersion>>() {}.getType();
			Result<AppVersion> result = gson.fromJson(json,type);
			if(null!=result&&result.getCode()==200){
				AppVersion appVersion = result.getData();
				int apkCode = Integer.valueOf(appVersion.getVersionCode());
				int versionCode = mContext.getPackageManager().getPackageInfo(
						mContext.getPackageName(), 0).versionCode;
				if (apkCode > versionCode) {
					needUpdate = true;
					if(null!=updateLinstener){
						apkUrl = "https://cdn.aiibt.cn/"+appVersion.getPath();
						updateLinstener.update(version,apkUrl,appVersion.getDesc());
					}
					handler.sendEmptyMessage(0);
				}else{
					if(isClick){
						handler.sendEmptyMessage(1);
					}
				}
			}
		} catch (PackageManager.NameNotFoundException ignored) {
		}
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(msg.what==0){
				showD(updateMessage, apkUrl);
			}else {
				Toast.makeText(mContext, R.string.lastest_version,Toast.LENGTH_LONG).show();
			}
		};
	};

	@SuppressLint("NewApi") private void showD(String msg, final String url) {
		
		LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        View v = layoutInflater.inflate(R.layout.update_dialog, null);
        final AlertDialog dialog = new AlertDialog.Builder(mContext,AlertDialog.THEME_HOLO_LIGHT)
                .setView(v).create();
        TextView contentTextView = (TextView) v.findViewById(R.id.update_content);
        contentTextView.setText(msg);
        v.findViewById(R.id.update_confim_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	goToDownload(url);
                dialog.dismiss();
            }
        });
        v.findViewById(R.id.update_confim_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        try{

			dialog.show();
			dialog.setView(v, 0, 0, 0, 0);
			dialog.setCancelable(true);
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	public void goToDownload(String url) {
		Intent intent = new Intent(mContext, ApkUpdateService.class);
		intent.putExtra(ApkUpdateService.APK_DOWNLOAD_URL, url);

//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//			mContext.startForegroundService(intent);
//		} else {
			mContext.startService(intent);
//		}
	}
	private UpdateLinstener updateLinstener;
	public void setUpdateLinstener(UpdateLinstener updateLinstener){
		this.updateLinstener = updateLinstener;
	}
	public interface UpdateLinstener{
		void update(String name,String url,String msg);
	}
}
